package cn.sys.service.impl;

import cn.sys.controller.dto.SearchDTO;
import cn.sys.dao.ManagerInfoDao;
import cn.sys.dao.NoticeDao;
import cn.sys.entity.ManagerInfo;
import cn.sys.entity.Notice;
import cn.sys.service.NoticeService;
import cn.sys.util.MybatisUtil;
import cn.sys.util.ResultData;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class NoticeServiceImpl implements NoticeService {
    private SqlSession sqlSession = MybatisUtil.getSQLSession();

    @Override
    public ResultData findNotices(SearchDTO searchDTO) {
        NoticeDao noticeDao = sqlSession.getMapper(NoticeDao.class);
        // 注意还要查出公告发布人的账号名，也封装进resultData中
        ManagerInfoDao managerInfoDao = sqlSession.getMapper(ManagerInfoDao.class);
        // 1. 开启分页操作
        PageHelper.startPage(searchDTO.getPageNum(), searchDTO.getPageSize(),searchDTO.getOrderBy());
        PageHelper.orderBy(searchDTO.getOrderBy());
        // 2. 调用持久层查询数据库中内容，因为要存管理员账号名，所以重新定义一个List<Map>集合存放信息
        List<Map<String, Object>> noticesAndManagers = new ArrayList<>();
        List<Notice> notices = noticeDao.findNotices(searchDTO);
        for (Notice notice : notices){
            Map<String, Object> map = new HashMap<>();
            map.put("noticeId", notice.getId());
            map.put("content", notice.getContent());
            map.put("createTime", notice.getCreateTime());
            map.put("type", notice.getType());
            // 查出管理员账号名
            ManagerInfo managerInfo = managerInfoDao.findManagerInfoById(notice.getManagerId());
            map.put("managerAccount", managerInfo.getAccount());
            noticesAndManagers.add(map);
        }
        // 3. 根据分页信息和公告内容，构建分页信息对象
        PageInfo<Notice> pageInfo = PageInfo.of(notices);

        // 4. 根据前端需要传入的内容，及内容的数据格式，构建resultData返回给前端
        ResultData resultData = new ResultData();
        resultData.put("result", true);
        resultData.put("msg", "");
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("currPage", searchDTO.getPageNum());
        pageMap.put("total", pageInfo.getTotal());
        pageMap.put("pageSize", searchDTO.getPageSize());
        resultData.put("pagination", pageMap);
        resultData.put("datas", noticesAndManagers);
        return resultData;
    }

    /**
     * 删除公告
     * @param noticeId 公告的ID
     * @return
     */
    @Override
    public ResultData deleteNotice(Integer noticeId) {
        NoticeDao noticeDao = sqlSession.getMapper(NoticeDao.class);
        int i = noticeDao.deleteNoticeById(noticeId);
        if(i>0){
            return ResultData.ok(ResultData.DELETE_NOTICE_SUCCESS, "删除成功");
        }
        return ResultData.fail(ResultData.DELETE_NOTICE_FAIL, "删除失败，请稍后再试");
    }

    @Override
    public ResultData findDetailNotice(Integer noticeId) {
        NoticeDao noticeDao = sqlSession.getMapper(NoticeDao.class);
        Map<String, Object> noticeInfo = noticeDao.findNoticeAndManagerById(noticeId);
        if(noticeInfo.isEmpty()){
            return ResultData.fail(ResultData.OPERATION_FAIL, "查看失败，请稍后再试");
        }
        ResultData resultData = new ResultData();
        resultData.put("code", ResultData.OPERATION_SUCCESS);
        resultData.put("noticeInfo", noticeInfo);
        return resultData;
    }

    /**
     * 添加公告
     * @param notice
     * @return
     */
    @Override
    public ResultData addNotice(Notice notice) {
        // 参考网页：https://www.cnblogs.com/BRSblackshoot/p/15367718.html
        NoticeDao noticeDao = sqlSession.getMapper(NoticeDao.class);
        // 添加公告，主键id将返回给notice的id中
        int i = noticeDao.addNotice(notice);
        if(i>0) {
            ResultData resultData = ResultData.ok(ResultData.OPERATION_SUCCESS, "发布成功");
            // 如果传入的type是1-临时公告，设置定时任务，3天之后删除
            if (notice.getType() == 1) {
                ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(30);
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        // 删除临时公告
                        int j = noticeDao.deleteNoticeById(notice.getId());
                        if(j > 0){
                            System.out.println("删除临时公告："+notice.getId());
                        }
                    }
                }, 20, TimeUnit.SECONDS);
                resultData.put("msg","发布成功，临时公告将于3天后删除");
            }
            return resultData;
        }
        return ResultData.fail(ResultData.OPERATION_FAIL, "操作失败，请稍后再试");
    }
}
